<template>
    <div class="map-container">
      <div id="mapBox" class="map-box"></div>
    </div>
</template>

<script>
import { isLocationOutOfChina, transformFromWGSToGCJ, transformFromGCJToBaidu } from '@/plugins/geolocation/geolocation.js';

export default {
  props: {
    locationData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      map: null,
      userMarker: null,
      centerMarker: null,
      circle: null,
      userLocation: null,
      targetLocation: {
        latitude: 39.9087,
        longitude: 116.3975,
        radius: 500
      }
    };
  },
  mounted() {
    this.initMap();
    if (this.locationData) {
      this.processCoordinates(this.locationData);
      this.updateTargetLocation(this.locationData);
    }
    this.getUserLocation();
  },
  methods: {
    initMap() {
      this.map = new BMapGL.Map("mapBox");
      const defaultPoint = new BMapGL.Point(116.3975, 39.9087);
      this.map.centerAndZoom(defaultPoint, 15);
      this.map.enableScrollWheelZoom(true);
    },
    updateTargetLocation(locationData) {
      this.targetLocation = {
        latitude: locationData.latitude,
        longitude: locationData.longitude,
        radius: locationData.range
      };
      this.drawCheckArea();
    },
    async getUserLocation() {
      try {
        const position = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 5000
          });
        });

        this.processCoordinates({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        });
      } catch (error) {
        console.error("定位失败:", error);
        this.useDefaultLocation();
      }
    },

    processCoordinates(coords) {
      let finalCoords = {...coords};

      if (!isLocationOutOfChina(coords.latitude, coords.longitude)) {
        const gcj02 = transformFromWGSToGCJ(coords.latitude, coords.longitude);
        finalCoords = transformFromGCJToBaidu(gcj02.latitude, gcj02.longitude);
      }

      this.userLocation = finalCoords;
      this.updateUserMarker();
      this.drawCheckArea();
    },

    updateUserMarker() {
      if (this.userMarker) this.map.removeOverlay(this.userMarker);

      const point = new BMapGL.Point(this.userLocation.longitude, this.userLocation.latitude);

      this.userMarker = new BMapGL.Marker(point, {draggable: false});
      this.map.addOverlay(this.userMarker);
      this.map.centerAndZoom(point, 17);

      const infoWindow = new BMapGL.InfoWindow(
          `您的位置<br/>经度：${this.userLocation.longitude.toFixed(6)}<br/>纬度：${this.userLocation.latitude.toFixed(6)}`,
          {
            offset: new BMapGL.Size(0, -30),
            enableHTML: true
          }
      );
      this.userMarker.addEventListener("click", () => {
        this.userMarker.openInfoWindow(infoWindow);
      });
    },

    drawCheckArea() {
      let targetCoords = {
        longitude: this.targetLocation.longitude,
        latitude: this.targetLocation.latitude
      };

      if (this.centerMarker) this.map.removeOverlay(this.centerMarker);
      const centerPoint = new BMapGL.Point(targetCoords.longitude, targetCoords.latitude);

      const centerIcon = new BMapGL.Icon(
          "//api.map.baidu.com/images/marker.png",
          new BMapGL.Size(20, 20),
          {anchor: new BMapGL.Size(10, 20)}
      );

      this.centerMarker = new BMapGL.Marker(centerPoint, {icon: centerIcon});
      this.map.addOverlay(this.centerMarker);

      if (this.circle) this.map.removeOverlay(this.circle);
      this.circle = new BMapGL.Circle(centerPoint, this.targetLocation.radius, {
        strokeColor: "#FF0000",
        fillColor: "#FF0000",
        strokeOpacity: 0.3,
        fillOpacity: 0.1,
        strokeWeight: 2
      });
      this.map.addOverlay(this.circle);
    },

    convertToBaidu(coords) {
      if (isLocationOutOfChina(coords.latitude, coords.longitude)) return coords;
      const gcj02 = transformFromWGSToGCJ(coords.latitude, coords.longitude);
      return transformFromGCJToBaidu(gcj02.latitude, gcj02.longitude);
    },

    useDefaultLocation() {
      this.processCoordinates({latitude: 39.9087, longitude: 116.3975});
    }
  }
};
</script>

<style scoped>
.map-container {
  position: relative;
  width: 300px;
  height: 300px;
  margin: 20px auto;
  border: 2px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.map-box {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
}
</style>